//
// Created by fengzijie on 14-5-28.
//
// 
//


#import "AccountManager.h"
#import "AccountModel.h"

static NSString *kTokenKey = @"userToken";
static NSString *kPhoneKey = @"userPhone";

@interface AccountManager ()

@property(nonatomic, readwrite) AccountModel *account;

@end

@implementation AccountManager {

}

- (id)init {
    self = [super init];
    if (self) {
        [self loadAccountFromCache];
        [self setupNotification];
    }
    return self;
}

- (void)dealloc {
    [self cleanupNotification];
}

- (void)loginWithSimpleAccount:(AccountModel *)account {
    self.account = account;
    [self persistenceAccountInfo];
    [self refreshAccountInfo];
    [[NSNotificationCenter defaultCenter] postNotificationName: ACCOUNT_DID_LOGIN_NOTIFICATION
                                                        object:nil
                                                      userInfo:nil];
}

- (void)logout {
    self.account = nil;
    if (_accountManagerDelegate && [_accountManagerDelegate respondsToSelector:@selector(accountManagerUserLogout)]) {
        [_accountManagerDelegate accountManagerUserLogout];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:ACCOUNT_WILLDID_LOGOUT_NOTIFICATION
                                                        object:nil
                                                      userInfo:nil];
}

- (void)refreshAccountInfo {
    __weak typeof (self) weakSelf = self;
    [ApiClient getAccountInfoDidFinishLoaded:^(AccountModel *account, NSString *path) {
        if ([account.status isEqual:@(1)]) {
            NSString *token = weakSelf.account.data.token;
            weakSelf.account = account;
            weakSelf.account.data.token = token;
            [weakSelf persistenceAccountInfo];
            [[NSNotificationCenter defaultCenter] postNotificationName: ACCOUNT_DID_UPDATED_NOTIFICATION
                                                                object:nil
                                                              userInfo:nil];
        } else {
            [weakSelf logout];
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        [weakSelf logout];
    }];
}

- (void)persistenceAccountInfo {
    if (![NSKeyedArchiver archiveRootObject:self.account toFile:[self pathOfCacheFile]]) {
        NSLog(@"error, cache account info failed!");
    }
}

#pragma mark Private
- (void)accountInfoDidUpdated:(AccountModel *)newAccount {
    NSString *token = self.account.data.token;
    self.account = newAccount;
    self.account.data.token = token;

    [self persistenceAccountInfo];
    [[NSNotificationCenter defaultCenter] postNotificationName:ACCOUNT_DID_UPDATED_NOTIFICATION
                                                        object:nil
                                                      userInfo:nil];
}

- (void)loadAccountFromCache {
    self.account = [NSKeyedUnarchiver unarchiveObjectWithFile:[self pathOfCacheFile]];
}

- (NSString *)pathOfCacheFile {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *libraryPath = [paths objectAtIndex:0];
    return [libraryPath stringByAppendingPathComponent:@"account_info.plist"];
}

#pragma mark Notification
- (void)setupNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(enterForegroundNotification)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    
}

- (void)cleanupNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)enterForegroundNotification {
    if (self.account.data.token) {
        [self refreshAccountInfo];
    }
}

@end